import React, { useState, useEffect, useMemo } from "react";
import useMarkdownTypingEffect from "../hooks/useMarkdownTypingEffect";
import "./MyMarkdownParser.css";

const MyMarkdownParser = ({ markdown }: { markdown: string }) => {
  // const htmlContent = useMarkdownTypingEffect(markdown);

  const markdownToHtmlMap = {
    "# ": (text: string) => `<h1>${text}</h1>`,
    "## ": (text: string) => `<h2>${text}</h2>`,
    "### ": (text: string) => `<h3>${text}</h3>`,
    "#### ": (text: string) => `<h4>${text}</h4>`,
    "##### ": (text: string) => `<h5>${text}</h5>`,
    "###### ": (text: string) => `<h6>${text}</h6>`,
    "> ": (text: string) => `<blockquote>${text}</blockquote>`,
    // "```": (text: string) => `<pre><code>${text}</code></pre>`,
    // "`": (text: string) => `<code>${text}</code>`,
    "** ": (text: string) => `<strong>${text}</strong>`,
    "* ": (text: string) => `<em>${text}</em>`,
    "~~ ": (text: string) => `<del>${text}</del>`,
    "--- ": () => `<hr/>`,
    "![": (text: string, alt: string) => `<img src="${text}" alt="${alt}"/>`,
    "[": (text: string, link: string) => `<a href="${link}">${text}</a>`,
  };
  const startCodeMap = {
    "```": (text: string) => `<pre><code>${text}`,
    "`": (text: string) => `<code>${text}`,
  };
  const endCodeMap = {
    "```": () => `</code></pre>`,
    "`": () => `</code>`,
  };

  const htmlContent = useMemo(() => {
    let result = markdown.split("\n");
    result = result.filter((line) => line.trim() !== "");
    // console.log("result", result);
    const html = result.map((line) => {
      const matchedKey =
        Object.keys(markdownToHtmlMap).find((key) => line.startsWith(key)) ||
        Object.keys(startCodeMap).find((key) => line.startsWith(key));
      const endKey = Object.keys(endCodeMap).find((key) => line.endsWith(key));
      // console.log("matchedKey", matchedKey);
      if (matchedKey) {
        if (endKey && endKey in endCodeMap) {
          return endCodeMap[endKey as keyof typeof endCodeMap]();
        }
        if (matchedKey in markdownToHtmlMap) {
          return markdownToHtmlMap[matchedKey as keyof typeof markdownToHtmlMap](line.slice(matchedKey.length).trim());
        }
        if (startCodeMap[matchedKey as keyof typeof startCodeMap]) {
          return startCodeMap[matchedKey as keyof typeof startCodeMap](line.slice(matchedKey.length).trim());
        }
      }
      return line;
    });
    // console.log("html", html);
    return html;
  }, [markdown]);
  return (
    <div
      dangerouslySetInnerHTML={{ __html: htmlContent.join('') }}
      className="markdown-content"
    />
  );
};

export default MyMarkdownParser;
